package com.liuya.common;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;

/**
 * 通过获取spring的配置信息，提供需要的常用方法。
 * @author liuya
 * @Date   2014-7-31
 *
 */
@Component("springUtils")
@Lazy(false)
public final class SpringUtils implements DisposableBean, ApplicationContextAware {
	private static ApplicationContext applicationContext;
	private static PropertiesUtil propertyConfigurer;
	public static ApplicationContext WEB_APP_CONTEXT;
	public static WebApplicationContext WEB_CONTEXT;

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	public void setPropertyConfigurer(PropertiesUtil propertyConfigurer) {
		this.propertyConfigurer = propertyConfigurer;
	}
	
	public PropertiesUtil getPropertyConfigurer() {
		return propertyConfigurer;
	}
	
	public void destroy() {
		applicationContext = null;
	}

	/**
	 * 返回Spring应用上下文，可在任何地方使用它以获取想要的Spring信息
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static Object getBean(String name) {
		Assert.hasText(name);
		return applicationContext.getBean(name);
	}

	public static <T> T getBean(String name, Class<T> type) {
		Assert.hasText(name);
		Assert.notNull(type);
		return applicationContext.getBean(name, type);
	}

	/**
	 * 返回消息内容，利用Spring的资源加载实现国际化，见详细配置。
	 * @param code
	 * @param args
	 * @return
	 */
	public static String getMessage(String code, Object... args) {
		LocaleResolver res = (LocaleResolver) getBean("localeResolver", LocaleResolver.class);
		Locale lcl = res.resolveLocale(null);
		return applicationContext.getMessage(code, args, lcl);
	}
	
	/**
	 * 返回Spring加载的properties文件中的内容
	 * @param name
	 * @return
	 */
	public static String getProperty(String name) {
		return propertyConfigurer.getString(name);
	}
	
	public static HttpServletRequest getHttpServletRequest() {
		RequestAttributes reqAttrs = RequestContextHolder.currentRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes) reqAttrs).getRequest();
		return request;
	}
}